package com.health.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.health.dao.OrderSettingMapper;
import com.health.pojo.OrderSetting;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Resource
    private OrderSettingMapper orderSettingMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(List<OrderSetting> orderSettingList) {
        for (OrderSetting orderSetting : orderSettingList) {
            handleOrderSetting(orderSetting);
        }
    }

    @Override
    public List<Map<String, Integer>> findByDate(Date date) {
        return orderSettingMapper.findByDate(date);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editNumber(OrderSetting orderSetting) {
        handleOrderSetting(orderSetting);
    }

    @Override
    public OrderSetting findByOrderDate(Date orderDate) {
        return orderSettingMapper.findByOrderDate(orderDate);
    }

    /**
     * 处理预约设置
     */
    private void handleOrderSetting(OrderSetting orderSetting) {
        //根据提交的预约日期，查询数据库
        OrderSetting orderSettingDb = orderSettingMapper.findByOrderDate(orderSetting.getOrderDate());

        if (orderSettingDb != null) {
            //数据库中存在，则判断上传的Excel设置中，可预约人数是否大于数据库中的已预约人数
            if (orderSetting.getNumber() < orderSettingDb.getReservations()) {
                //小于，则抛出异常
                String orderDate = new SimpleDateFormat("yyyy/MM/dd")
                        .format(orderSetting.getOrderDate());
                throw new RuntimeException("可预约人数不能小于已预约人数，" +
                        orderDate + "已预约人数" + orderSettingDb.getReservations());
            } else if (orderSetting.getNumber() != orderSettingDb.getNumber()) {
                //不小于，并且提交的 与 数据库中的可预约人数不一致，则更新
                orderSettingMapper.updateNumber(orderSetting);
            }
        } else {
            //数据库中不存在，则添加该预约设置
            orderSettingMapper.add(orderSetting);
        }
    }
}
